//
//  MainViewController.m
//  LoveAttention
//
//  Created by 鞠超 on 15/12/29.
//  Copyright © 2015年 JC. All rights reserved.
//

#import "MainViewController.h"
#import "CollectionViewCell_9.h"
#import "LoginViewController.h"
#import "RechargeViewController.h"
#import "MyjifenViewController.h"
#import "AttentionTableViewController.h"
#import "ReservationTableViewController.h"
#import "ReservationOKTableViewController.h"
#import "InviteViewController.h"
#import "CardRechargeViewController.h"
#import "CardDataViewController.h"
#import "CardDallocTableViewController.h"
#import "UIImageView+WebCache.h"
#import "DataProvider.h"
#import "SVProgressHUD.h"
#import "ConfirmOrdersViewController.h"
#import "VPImageCropperViewController.h"

#import "DingdanliebiaoViewController.h"
#import "CtrlCodeScan.h"
#import "CardDetialViewController.h"
#import "HHAlertView.h"
#import "UploadFirstViewController.h"

//#define KURL @"http://115.28.67.86:8080/aigz/"
#define umeng_app_key @"557e958167e58e0b720041ff"
//#define KIMGURL @"http://115.28.67.86:8080/aigz/upload/"
#define ORIGINAL_MAX_WIDTH 640.0f

@interface MainViewController () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout , UIImagePickerControllerDelegate, UINavigationControllerDelegate,VPImageCropperDelegate,UIActionSheetDelegate,CtrlCodeScanDelegate,HHAlertViewDelegate>
@property (nonatomic, strong) UIImageView *portraitImageView;

@end

@implementation MainViewController
{
    UIButton *btn_backGround;
}

#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    btn_backGround=[[UIButton alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    btn_backGround.backgroundColor=[UIColor colorWithRed:38/255.0 green:38/255.0 blue:38/255.0 alpha:0.3];
    [[HHAlertView shared] setDelegate:self];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(login_inOK) name:@"Login_Success" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showalertView) name:@"UpoladInfoSuccess" object:nil];
    [self p_navigationController];
    //总的scorllview
    [self p_setupView];
    //登陆和积分布局
    [self p_setupView1];
    //充值和积分
    [self p_setupView2];
    //下面的9宫格
    [self p_setupView3];
    
    
    NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];
    if([[userdefault objectForKey:@"password"] length] != 0 && [[userdefault objectForKey:@"account"] length] != 0)
    {
        DataProvider * dataprovider=[[DataProvider alloc] init];
        [dataprovider setDelegateObject:self setBackFunctionName:@"Login_inCall:"];
        [dataprovider Login_inwith:[userdefault objectForKey:@"account"] andpwd:[userdefault objectForKey:@"password"]];
    }else
    {
        self.navigationItem.rightBarButtonItem = nil;
        self.btn_login.userInteractionEnabled = YES;
        [self.btn_login setTitle:@" 登录 " forState:(UIControlStateNormal)];
        self.image_head.image = [UIImage imageNamed:@"头像"];
        self.label_Sales.text = @"0.00";
        self.label_income.text = @"0.00";
        self.label_consume.text = @"0.00";
        
        NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];
        [userdefault setObject:@"Login_cancal" forKey:@"Login_Success"];
        
        self.collectionView.userInteractionEnabled = NO;
        self.btn_jifen.userInteractionEnabled = NO;
        self.btn_chong.userInteractionEnabled = NO;
        self.btn_headImage.userInteractionEnabled = NO;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




#pragma mark - navigationController
- (void)p_navigationController
{
//    self.navigationItem.title = @"商户版";
    
    //设置NavigationBar背景颜色
#warning 判断是否处于登录状态，要不要显示退出
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出" style:(UIBarButtonItemStyleDone) target:self action:@selector(rightBarButtonItemAction:)];
//     self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
}
//点击事件
- (void)rightBarButtonItemAction:(UIBarButtonItem *)bar
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示!" message:@"您确定要退出该账号吗" preferredStyle:(UIAlertControllerStyleAlert)];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
    UIAlertAction * action_ok = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        //退出账户， 隐藏退出
        self.navigationItem.rightBarButtonItem = nil;
        self.btn_login.userInteractionEnabled = YES;
        [self.btn_login setTitle:@" 登录 " forState:(UIControlStateNormal)];
        self.image_head.image = [UIImage imageNamed:@"头像"];
        self.label_Sales.text = @"0.00";
        self.label_income.text = @"0.00";
        self.label_consume.text = @"0.00";
        
        NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];
        [userdefault setObject:@"Login_cancal" forKey:@"Login_Success"];
        
        self.collectionView.userInteractionEnabled = NO;
        self.btn_jifen.userInteractionEnabled = NO;
        self.btn_chong.userInteractionEnabled = NO;
        self.btn_headImage.userInteractionEnabled = NO;
        
        
        //保存用户名和密码
        [userdefault setObject:@"" forKey:@"account"];
        [userdefault setObject:@"" forKey:@"password"];
        
    }];
    
    UIAlertAction * action_cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        //不做任何操作
    }];
    
    [alert addAction:action_cancel];
    [alert addAction:action_ok];
}

#pragma mark - scorllview(总载体)
- (void)p_setupView
{
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
    //这个后面可以改
    //    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, 1000);
    self.scrollView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    [self showalertView];
}
-(void)showalertView
{
    
    DLog(@"%@",get_sp(@"errcode"));
    if ([get_sp(@"errcode") isEqualToString:@"1111"]) {
        [self.view addSubview:btn_backGround];
        [HHAlertView showAlertWithStyle:HHAlertStyleWraing inView:self.view Title:@"" detail:get_sp(@"errdesc") cancelButton:@"退出" Okbutton:@"填写资料"];
    }
    else if ([get_sp(@"errcode") isEqualToString:@"2222"])
    {
        [self.view addSubview:btn_backGround];
        [HHAlertView showAlertWithStyle:HHAlertStyleDefault inView:self.view Title:@"" detail:get_sp(@"errdesc") cancelButton:@"退出" Okbutton:@"等待"];
    }
}

#pragma mark - 登陆和积分布局
- (void)p_setupView1
{
    UIImageView * topBackImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
    topBackImage.image = [UIImage imageNamed:@"login_bg02"];
    [self.scrollView addSubview:topBackImage];
    
    //头像
    self.image_head = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 25, 10, 50, 50)];
    self.image_head.layer.cornerRadius = 25;
    self.image_head.image = [UIImage imageNamed:@"头像"];
    self.image_head.userInteractionEnabled = YES;
    self.image_head.layer.masksToBounds = YES;
    [topBackImage addSubview:self.image_head];
    
    UIButton * btn_head = [UIButton buttonWithType:(UIButtonTypeSystem)];
    btn_head.frame = CGRectMake(self.view.frame.size.width / 2 - 30, 10, 60, 60);
    [self.scrollView addSubview:btn_head];
    self.btn_headImage = btn_head;
    [btn_head addTarget:self action:@selector(Btn_touxiangClick) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.btn_login = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.btn_login.frame = CGRectMake(self.view.frame.size.width / 2 - 45, CGRectGetMaxY(self.image_head.frame), 90, 25);
    [self.btn_login setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [self.btn_login setTitle:@" 登录 " forState:(UIControlStateNormal)];
    [self.scrollView addSubview:self.btn_login];
    [self.btn_login addTarget:self action:@selector(btn_loginAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    CGFloat distance = (self.view.frame.size.width - 300) / 4;
    
    UILabel * label1 = [[UILabel alloc] initWithFrame:CGRectMake(distance + 3, CGRectGetMaxY(self.btn_login.frame) + 5, 47, 30)];
    label1.text = @"总收入:";
//    label1.backgroundColor = [UIColor orangeColor];
    label1.font = [UIFont systemFontOfSize:14];
    label1.textColor = [UIColor whiteColor];
    [self.scrollView addSubview:label1];
    //收入值
    self.label_income = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label1.frame) + 0, CGRectGetMaxY(self.btn_login.frame) + 5, 53, 30)];
    self.label_income.text = @"0.00";
    self.label_income.font = [UIFont systemFontOfSize:13];
    self.label_income.textColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.label_income];
    
    
    UILabel * label2 = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.label_income.frame) + distance, CGRectGetMaxY(self.btn_login.frame) + 5, 47, 30)];
    label2.text = @"消费券:";
    label2.font = [UIFont systemFontOfSize:14];
    label2.textColor = [UIColor whiteColor];
    [self.scrollView addSubview:label2];
    //消费券
    self.label_consume = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label2.frame) + 0, CGRectGetMaxY(self.btn_login.frame) + 5, 53, 30)];
    self.label_consume.text = @"0.00";
    self.label_consume.font = [UIFont systemFontOfSize:13];
    self.label_consume.textColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.label_consume];
    
    
    UILabel * label3 = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.label_consume.frame) + distance, CGRectGetMaxY(self.btn_login.frame) + 5, 47, 30)];
    label3.text = @"销售券:";
    label3.font = [UIFont systemFontOfSize:14];
    label3.textColor = [UIColor whiteColor];
    [self.scrollView addSubview:label3];
    //销售券
    self.label_Sales = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label3.frame) + 0, CGRectGetMaxY(self.btn_login.frame) + 5, 53, 30)];
    self.label_Sales.text = @"0.00";
    self.label_Sales.font = [UIFont systemFontOfSize:13];
    self.label_Sales.textColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.label_Sales];
    
}

#pragma mark - 充值和积分
- (void)p_setupView2
{
    //充值
    UIView * view_chong = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.label_income.frame) + 3, self.view.frame.size.width / 2 - 1, 50)];
    view_chong.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:view_chong];
    
    UIImageView * image_chong = [[UIImageView alloc] initWithFrame:CGRectMake(30, 0, 50, 50)];
    image_chong.image = [UIImage imageNamed:@"充值"];
    [view_chong addSubview:image_chong];
    
    UILabel * label_chong = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(image_chong.frame) + 10, 10, 50, 30)];
    label_chong.text = @"充值";
    [view_chong addSubview:label_chong];
    
    UIButton * btn_chong = [UIButton buttonWithType:(UIButtonTypeSystem)];
    btn_chong.frame = CGRectMake(0, CGRectGetMaxY(self.label_income.frame) + 3, self.view.frame.size.width / 2 - 1, 50);
    [self.scrollView addSubview:btn_chong];
    [btn_chong addTarget:self action:@selector(btn_chongAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.btn_chong = btn_chong;

    
    //积分
    UIView * view_jifen = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 + 2, CGRectGetMaxY(self.label_income.frame) + 3, self.view.frame.size.width / 2 - 1, 50)];
    view_jifen.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:view_jifen];
    
    UIImageView * image_jifen = [[UIImageView alloc] initWithFrame:CGRectMake(30, 0, 50, 50)];
    image_jifen.image = [UIImage imageNamed:@"积分psd"];
    [view_jifen addSubview:image_jifen];
    
    UILabel * label_jifen = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(image_jifen.frame) + 10, 10, 50, 30)];
    label_jifen.text = @"积分";
    [view_jifen addSubview:label_jifen];
    
    UIButton * btn_jifen = [UIButton buttonWithType:(UIButtonTypeSystem)];
    btn_jifen.frame = CGRectMake(self.view.frame.size.width / 2 + 2, CGRectGetMaxY(self.label_income.frame) + 3, self.view.frame.size.width / 2 - 1, 50);
    [self.scrollView addSubview:btn_jifen];
    [btn_jifen addTarget:self action:@selector(btn_jifenAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.btn_jifen = btn_jifen;
}

#pragma mark - 下面的九宫格
- (void)p_setupView3
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(80, 80);
    if(self.view.frame.size.width == 414)
    {
        layout.itemSize = CGSizeMake(100, 100);
    }
    layout.sectionInset = UIEdgeInsetsMake(20, 20, 0, 20);
    
    
    if(self.view.frame.size.width == 414)
    {
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.label_income.frame) + 60, self.view.frame.size.width, 550) collectionViewLayout:layout];
    }
    else
    {
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.label_income.frame) + 60, self.view.frame.size.width, 450) collectionViewLayout:layout];
    }
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    //注册
    [self.collectionView registerClass:[CollectionViewCell_9 class] forCellWithReuseIdentifier:@"cell_9"];
    
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, CGRectGetMaxY(self.collectionView.frame) + 0);
}

#pragma mark - collectionView代理
- (NSInteger )numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 7;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell_9 * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell_9" forIndexPath:indexPath];
    
    switch (indexPath.row) {
        case 0:
        {
            cell.image.image = [UIImage imageNamed:@"扫描二维码"];
        }
            break;
        case 1:
        {
            cell.image.image = [UIImage imageNamed:@"dingdanzhongxin"];
        }
            break;
        case 2:
        {
            cell.image.image = [UIImage imageNamed:@"关注用户"];
        }
            break;
        case 3:
        {
            cell.image.image = [UIImage imageNamed:@"我的邀请"];
        }
            break;
        case 4:
        {
            cell.image.image = [UIImage imageNamed:@"卡券充值"];
        }
            break;
        case 5:
        {
            cell.image.image = [UIImage imageNamed:@"卡券数据"];
        }
            break;
        case 6:
        {
            cell.image.image = [UIImage imageNamed:@"卡券核销"];
        }
            break;
        default:
            break;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {//扫描二维码
//            ErWeiMaViewController * erWeiMaViewController = [[ErWeiMaViewController alloc] initWithNibName:@"ErWeiMaViewController" bundle: [NSBundle mainBundle]];
//            [self showViewController:erWeiMaViewController sender:nil];
            
            CtrlCodeScan * scanCode=[[CtrlCodeScan alloc] initWithNibName:@"CtrlCodeScan" bundle:[NSBundle mainBundle]];
            scanCode.delegate=self;
            [self.navigationController presentViewController:scanCode animated:YES completion:nil];
        }
            break;
        case 1:
        {//请输入订单验证码
//#warning 这个不行的话可以再改
            
            DingdanliebiaoViewController * dingdanliebiaoViewController = [[DingdanliebiaoViewController alloc] init];
            
            [self showViewController:dingdanliebiaoViewController sender:nil];
            
//            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请输入订单验证码" message:@"提示" preferredStyle:(UIAlertControllerStyleAlert)];
//            
//            [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
//                textField.placeholder = @"请输入订单验证码";
//                textField.clearButtonMode = UITextFieldViewModeWhileEditing;
////                textField.layer.borderColor = [UIColor grayColor].CGColor;
////                textField.layer.borderWidth = 1;
//            }];
//
//            UIAlertAction * action_ok = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//                
//                UITextField * textField = alert.textFields.firstObject;
//                NSLog(@"%@",textField.text);
//                
//                DataProvider * dataprovider=[[DataProvider alloc] init];
//                [dataprovider setDelegateObject:self setBackFunctionName:@"inputCaptcha:"];
//                [dataprovider inputCaptchaWith:textField.text];
//                
//
//                
//            }];
//            
//            UIAlertAction * action_cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
//                //不做任何操作
//                
////#warning +++ 先跳这个
////                ConfirmOrdersViewController * confirmOrdersViewController = [[ConfirmOrdersViewController alloc] init];
////                
////                [self showViewController:confirmOrdersViewController sender:nil];
//            }];
//            
//            [alert addAction:action_cancel];
//            [alert addAction:action_ok];
//            
//            [self presentViewController:alert animated:YES completion:^{
//                
//            }];
        }
            break;
        case 2:
        {//关注用户
            AttentionTableViewController * attentionTableViewController = [[AttentionTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
            
            [self showViewController:attentionTableViewController sender:nil];
            
        }
            break;
//        case 3:
//        {//预约用户
//            ReservationTableViewController * reservationTableViewController = [[ReservationTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
//            
//            [self showViewController:reservationTableViewController sender:nil];
//        }
//            break;
//        case 4:
//        {//预约确定
//            ReservationOKTableViewController * reservationOKTableViewController = [[ReservationOKTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
//            
//            [self showViewController:reservationOKTableViewController sender:nil];
//            
//        }
//            break;
        case 3:
        {//我的邀请
            InviteViewController * inviteViewController = [[InviteViewController alloc] init];
            
            [self showViewController:inviteViewController sender:nil];
            
        }
            break;
        case 4:
        {//卡券充值
#warning 文档和UI中没有给出明确的说明
//            NSLog(@"卡券充值");
//            CardRechargeViewController * cardRechargeViewController = [[CardRechargeViewController alloc] init];
//            
//            [self showViewController:cardRechargeViewController sender:nil];
            
            RechargeViewController * rechargeViewController = [[RechargeViewController alloc] init];
            [self showViewController:rechargeViewController sender:nil];
            
        }
            break;
        case 5:
        {//卡券数据
            
            CardDataViewController * cardDataViewController = [[CardDataViewController alloc] init];
            [self showViewController:cardDataViewController sender:nil];
        }
            break;
        case 6:
        {//卡券核销
            
            CardDallocTableViewController * cardDallocTableViewController = [[CardDallocTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
            
            [self showViewController:cardDallocTableViewController sender:nil];
        }
            break;
        default:
            break;
    }
}

- (void)didCodeScanOk:(id)info
{
    if([info containsString:@"http"])
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:info]];
        
    }
    else
    {
        CardDetialViewController * cardDetialViewController = [[CardDetialViewController alloc] init];
        cardDetialViewController.couponid = info;
        
        [self showViewController:cardDetialViewController sender:nil];
       
    }
}

#pragma mark - 头像的点击事件
- (void)btn_image_headAction:(UIButton *)sender
{
    //    NSLog(@"点击头像");
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择图片类型" preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
    UIAlertAction * action_photo = [UIAlertAction actionWithTitle:@"本地照片" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        //创建图片控制器
        UIImagePickerController * pick = [[UIImagePickerController alloc] init];
        pick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //是否允许编辑
        pick.allowsEditing = YES;
        //代理
        pick.delegate = self;
        [self presentViewController:pick animated:YES completion:^{
            
        }];
    }];
    
    UIAlertAction * action_play = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        //创建图片控制器
        UIImagePickerController * pick = [[UIImagePickerController alloc] init];
        pick.sourceType = UIImagePickerControllerSourceTypeCamera;
        //是否允许编辑
        pick.allowsEditing = YES;
        //代理
        pick.delegate = self;
        [self presentViewController:pick animated:YES completion:^{
            
        }];
        
    }];
    
    UIAlertAction * action_cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action_photo];
    [alert addAction:action_play];
    [alert addAction:action_cancel];
}

//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
//{
//    //这个是被编辑过的,
//    self.image_head.layer.masksToBounds = YES; //很重要
//    self.image_head.layer.cornerRadius = 25;
//    self.image_head.image = info[UIImagePickerControllerOriginalImage];    
//    //退出!!
//    [self dismissViewControllerAnimated:YES completion:^{
//        
//        DataProvider * dataprovider = [[DataProvider alloc] init];
//        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
////
//        [dataprovider setDelegateObject:self setBackFunctionName:@"Image_headAction:"];
////
//        NSData * data = [NSData dataWithContentsOfURL:info[UIImagePickerControllerMediaURL]];
//        
//        [dataprovider Image_headwith:[defaults objectForKey:@"merchantid"] andfiles:data];
//    }];
//}


//  接口      [dataprovider Image_headwith:[defaults objectForKey:@"merchantid"] andfiles:data];

//  图片信息  self.image_head
// 只是缺少图片数据 （自己好好想想）














#pragma mark - 登陆btn
- (void)btn_loginAction:(UIButton *)sender
{
    //    NSLog(@"登陆一下");
    
    NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];
    if([[userdefault objectForKey:@"Login_Success"] isEqualToString:@"Login_Success"])
    {
        sender.userInteractionEnabled = NO;
    }
    else
    {
        LoginViewController * loginViewController = [[LoginViewController alloc] init];
        [self showViewController:loginViewController sender:nil];
    }
}

#pragma mark - btn 充值和积分点击事件
- (void)btn_chongAction:(UIButton *)sender
{
//    NSLog(@"充值");
    RechargeViewController * rechargeViewController = [[RechargeViewController alloc] init];
    [self showViewController:rechargeViewController sender:nil];
}

- (void)btn_jifenAction:(UIButton *)sender
{
//    NSLog(@"积分");
    MyjifenViewController * myjifenViewController = [[MyjifenViewController alloc] init];
    [self showViewController:myjifenViewController sender:nil];
}

#pragma mark - 登陆成功
- (void)login_inOK
{
    self.collectionView.userInteractionEnabled = YES;
    self.btn_jifen.userInteractionEnabled = YES;
    self.btn_chong.userInteractionEnabled = YES;
    self.btn_headImage.userInteractionEnabled = YES;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出" style:(UIBarButtonItemStyleDone) target:self action:@selector(rightBarButtonItemAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    NSUserDefaults * userdefault=[NSUserDefaults standardUserDefaults];

    [self.btn_login setTitle:[userdefault objectForKey:@"name"] forState:(UIControlStateNormal)];
    
    self.image_head.layer.masksToBounds = YES; //很重要
    self.image_head.layer.cornerRadius = 25;

        NSString *url = [NSString stringWithFormat:@"%@upload/%@",Url,[userdefault objectForKey:@"imgpath"]];
        
    [self.image_head sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"头像"]];


    if([[userdefault objectForKey:@"totalIncome"] isEqualToString:@"<null>"])
    {
        self.label_consume.text = @"0.00";
    }
    else
    {
        self.label_income.text = [userdefault objectForKey:@"totalIncome"];
    }
    
    if([[userdefault objectForKey:@"sellprice"] isEqualToString:@"<null>"])
    {
        self.label_consume.text = @"0.00";
    }
    else
    {
        self.label_consume.text = [userdefault objectForKey:@"sellprice"];
    }
    
    if([[userdefault objectForKey:@"sellnum"] isEqualToString:@"<null>"])
    {
        self.label_Sales.text = @"0.00";
    }
    else
    {
        self.label_Sales.text = [userdefault objectForKey:@"sellnum"];
    }
    
//    self.label_income.text = [userdefault objectForKey:@"totalIncome"];
//    self.label_consume.text = [userdefault objectForKey:@"sellprice"];
//    self.label_Sales.text = [userdefault objectForKey:@"sellnum"];
    
}

- (void)Login_inCall:(id )dict
{
    NSLog(@"%@",dict);
    
    if ([dict[@"status"][@"succeed"] intValue] == 1) {
        
        @try {
                        
            NSUserDefaults * userdefault=[NSUserDefaults standardUserDefaults];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"categoryid"]] forKey:@"categoryid"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"merchantid"]] forKey:@"merchantid"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"memberid"]] forKey:@"memberid"];

            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"address"]] forKey:@"address"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"announcement"]] forKey:@"announcement"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"avatar"]] forKey:@"imgpath"];
            
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"isrebate"]] forKey:@"isrebate"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"mdesc"]] forKey:@"mdesc"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"name"]] forKey:@"name"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"opentime"]] forKey:@"opentime"];
            
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"rebaterate"]] forKey:@"rebaterate"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"remark"]] forKey:@"remark"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"sellnum"]] forKey:@"sellnum"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"sellprice"]] forKey:@"sellprice"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"telephone"]] forKey:@"telephone"];
            [userdefault setObject:[NSString stringWithFormat:@"%@",dict[@"data"][@"totalIncome"]] forKey:@"totalIncome"];
            
            [userdefault setObject:@"Login_Success" forKey:@"Login_Success"];

            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Login_Success" object:nil];
        }
        @catch (NSException *exception) {
            NSLog(@"保存userdefault出错");
        }
        @finally {
            
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
        
        
        self.navigationItem.rightBarButtonItem = nil;
        self.btn_login.userInteractionEnabled = YES;
        [self.btn_login setTitle:@" 登录 " forState:(UIControlStateNormal)];
        self.image_head.image = [UIImage imageNamed:@"头像"];
        self.label_Sales.text = @"0.00";
        self.label_income.text = @"0.00";
        self.label_consume.text = @"0.00";
        
        NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];
        [userdefault setObject:@"Login_cancal" forKey:@"Login_Success"];
        
        self.collectionView.userInteractionEnabled = NO;
        self.btn_jifen.userInteractionEnabled = NO;
        self.btn_chong.userInteractionEnabled = NO;
        self.btn_headImage.userInteractionEnabled = NO;
        
    }
}

#pragma mark - 验证验证码
- (void)inputCaptcha:(id )dict
{
    NSLog(@"%@",dict);
    
    if ([dict[@"status"][@"succeed"] intValue]==1) {
        @try
        {
            [SVProgressHUD showSuccessWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
            
            //跳到确认订单页
            ConfirmOrdersViewController * confirmOrdersViewController = [[ConfirmOrdersViewController alloc] init];
            confirmOrdersViewController.orderid = dict[@"data"][@"orderid"];
            [self showViewController:confirmOrdersViewController sender:nil];
        }
        @catch (NSException *exception) {
            
        }
        @finally {
            
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
    }

    
}

#pragma mark - 头像的上传
- (void)Image_headAction:(id )dict
{
    NSLog(@"%@",dict);
    if ([dict[@"status"][@"succeed"] intValue]==1) {
        @try
        {
            
            [SVProgressHUD showSuccessWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
        }
        @catch (NSException *exception) {
            
        }
        @finally {
            
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
    }
}













/********************************上传图片开始*************************************/

-(void)Btn_touxiangClick
{
    NSLog(@"上传图片");
    [self editPortrait];
}

- (void)editPortrait {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    self.portraitImageView.image = editedImage;
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
        [self saveImage:editedImage withName:@"avatar.jpg"];
        
//        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"avatar.jpg"];
//        NSLog(@"选择完成");
//        [SVProgressHUD showWithStatus:@"加载中.." maskType:SVProgressHUDMaskTypeBlack];
//        //        NSData* imageData = UIImagePNGRepresentation(editedImage);
//        DataProvider * dataprovider=[[DataProvider alloc] init];
//        [dataprovider setDelegateObject:self setBackFunctionName:@"UploadBackCall:"];
//        [dataprovider UpLoadImage:fullPath andkey:userinfoWithFile[@"key"]];
        NSData *imageData = UIImagePNGRepresentation(editedImage);
        
        [SVProgressHUD showWithStatus:@"请稍等..." maskType:SVProgressHUDMaskTypeBlack];
        DataProvider *dataProvider = [[DataProvider alloc] init];
        [dataProvider setDelegateObject:self setBackFunctionName:@"UploadBackCall:"];
        [dataProvider Image_headwith:get_sp(@"merchantid") andfiles:imageData];
    }];
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}
#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}
- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}
-(void)UploadBackCall:(id)dict
{
    NSLog(@"%@",dict);
    //    [img_touxiang setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KURL,dict[@"data"][@"url"]]]]]
    //     ];
    [SVProgressHUD dismiss];
    if ([dict[@"status"][@"succeed"] intValue]==1) {
        //准备刷新头像
        [SVProgressHUD showSuccessWithStatus:@"图片上传成功" maskType:SVProgressHUDMaskTypeBlack];
        
        set_sp(@"imgpath", dict[@"data"][@"imgurl"]);
        
        NSString *url = [NSString stringWithFormat:@"%@upload/%@",Url,get_sp(@"imgpath")];
        [self.image_head sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"头像"]];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"上传失败，请重新上传" maskType:SVProgressHUDMaskTypeBlack];
    }
}

/*************************************上传图片结束******************************************/


#pragma mark HHAlertViewDelegate
- (void)didClickButtonAnIndex:(HHAlertButton)button
{
    if (button == HHAlertButtonOk&&![get_sp(@"errcode") isEqualToString:@"2222"]) {
        NSLog(@"ok Button is seleced use delegate");
        UploadFirstViewController * uploadfirst=[[UploadFirstViewController alloc] initWithNibName:@"UploadFirstViewController" bundle:[NSBundle mainBundle]];
        [self showViewController:uploadfirst sender:nil];
    }
    else if(button == HHAlertButtonOk&&[get_sp(@"errcode") isEqualToString:@"2222"])
    {
//        NSLog(@"cancel Button is seleced use delegate");
        
    }
    else
    {
        LoginViewController * loginViewController = [[LoginViewController alloc] init];
        [self showViewController:loginViewController sender:nil];
    }
    [btn_backGround removeFromSuperview];
}


@end
